package com.sheep.opt;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.sheep.opt.ThreadUtil;
import org.apache.struts2.StrutsStatics;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: wnj
 * Date: 2010-11-3
 * Time: 9:41:06
 * To change this template use File | Settings | File Templates.
 */
public class MainInterceptor extends AbstractInterceptor {
    //@Override
    public String intercept(ActionInvocation invocation) throws Exception {
        ActionContext actionContext = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
        HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
        HttpSession session=request.getSession();

        ThreadUtil.setHttpSession(session);

        try{
            if(((AbstractAction)invocation.getAction()).isForceLogin()){
                if(session.getAttribute("host") == null){
                    return Action.LOGIN;
                }
            }

            if(!((AbstractAction)invocation.getAction()).isAuthorized()){
                return "denied";
            }
        }catch(Exception e){
            return "denied";
        }
        
        try{
            String res = invocation.invoke();//启动action
            cleanupThreadutil();
            return res;
        }
        finally{
            cleanupThreadutil();            
        }
    }
    
    private void cleanupThreadutil() {
        try {
            ThreadUtil.closeAll();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }        
    }
}
